package com.xuanrui.interceptor;



import com.xuanrui.commons.enums.BusinessExceptionEnum;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Service(value = "loginInterceptor")
public class LoginInterceptor extends HandlerInterceptorAdapter {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        if("GET".equalsIgnoreCase(request.getMethod())){
            response.setStatus(200);
            //  chain.doFilter(request, response);
            return true;
        }
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(200);
            //  chain.doFilter(request, response);
            return true;
        }


        String header = request.getHeader("wechatauthorization");

        if (header == null || !header.startsWith("wechat ")) {

            noLogin(response);


            return false;
        }

        try {
            Jwts.parser()
                    .setSigningKey("mySecret")
                    .parseClaimsJws(header.replace("wechat ", ""))
                    .getBody()
                    .getSubject();


            return true;

        } catch (Exception e) {

        }


        noLogin(response);
        return false;


    }


    private void noLogin(HttpServletResponse response) {
        response.setContentType("application/json;charset = UTF-8");
        String msg = "用户未登录";
        int code = BusinessExceptionEnum.NOT_LOGIN.getCode();
        try {


            response.setContentType("application/json;charset = UTF-8");

            response.getWriter().print("{\"errorCode\":" + code + ",\"message\":\"" + msg + "\",\"data\":{\"code\":" + code + "},\"success\":false}");


            response.getWriter().flush();
        } catch (Exception e) {

        }

    }

}
